const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8080 });

// 存储所有连接的客户端
const clients = new Set();

wss.on('connection', (ws) => {
  // 添加新客户端到集合
  clients.add(ws);
  console.log('新客户端连接');

  // 处理接收到的消息
  ws.on('message', (message) => {
    console.log('收到消息:', message);
    
    // 广播消息给所有客户端
    clients.forEach((client) => {
      if (client !== ws && client.readyState === WebSocket.OPEN) {
        client.send(message);
      }
    });
  });

  // 处理连接关闭
  ws.on('close', () => {
    clients.delete(ws);
    console.log('客户端断开连接');
  });
});

console.log('WebSocket服务器运行在端口8080');  